package com.cykj.interceptoer;


import com.alibaba.fastjson.JSON;
import com.cykj.commonData.CommonData;
import com.cykj.dto.ResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: Psychology
 * @BelongsPackage: com.cykj.interceptoer
 * @Author: 小林
 * @CreateTime: 2025-02-03 13:28
 * @Description: Token
 * @Version: 1.0
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1、从请求头里获取token信息
         String token = request.getHeader("jd_token");
        //2、判断这个token是否有空，如果有空 拦截 给用户进行反馈
        if (token == null || token.isEmpty()) {
             ResponseDTO responseDTO = new ResponseDTO(-2, "请携带token", null);
             //解决中文乱码
            response.setContentType("text/html;charset=utf-8");
             response.getWriter().write(JSON.toJSONString(responseDTO));
             return false;
        }

        //3、验证token 是否过期 ===》redis 的key是否过期，如果过期，拦截给用户反馈
        if(!redisTemplate.hasKey(token)) {
             ResponseDTO responseDTO = new ResponseDTO(-2, "token过期", null);
            //解决中文乱码
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(responseDTO));
        }
        //4、更新时间，更新token时间
        redisTemplate.expire(token, CommonData.TOKEN_REDIS_EXPIRE_TIME, TimeUnit.DAYS);


        return true;
    }
}

